/**
 * 
 */
package vn.lumi.smarthome.ui;


import vn.lumi.smarthome.LumiHome;
import vn.lumi.smarthome.R;
import vn.lumi.smarthome.network.NetMessage;
import vn.lumi.smarthome.service.SmartHomeService;
import vn.lumi.smarthome.ulti.Preference;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.graphics.Typeface;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;

import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

/**
 * @author hieu
 * 
 */
public class SettingActivity extends SherlockFragmentActivity implements OnClickListener,
		ServiceConnection {
	private static final int STATUS = 1;
	private static final int PROGRESS_DIALOG_ID = 2;
	CountDownTimer mTimer = null;

	private boolean stateActivity = false;
	// ProgressDialog mDialogProgress = null;
	// bind Service
	private ServiceConnection mConnection = (ServiceConnection) this;
	private Messenger mServiceMessenger = null;
	// private final Messenger mMessenger = new Messenger(new
	// IncomingMessageHandler());
	boolean mIsBound;
	BroadcastReceiver mReceiver;
	// End
	String pwd;
	EditText currenPwd,newPwd,confirmPwd,account;
	TextView logOut;
	Button ok;
	
//	MenuItem setting,logOut;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_dialog_pwd);
		ok = (Button) findViewById(R.id.activity_dialog_pwd_btn_ok);
		ok.setOnClickListener(this);
		 currenPwd = (EditText) findViewById(R.id.activity_dialog_pwd_current_pwd);
		 newPwd = (EditText) findViewById(R.id.activity_dialog_pwd_new_pwd);
		 confirmPwd = (EditText) findViewById(R.id.activity_dialog_pwd_confirm_pwd);
		 account =(EditText)findViewById(R.id.activity_dialog_pwd_username);
		 account.setText(Preference.getUID(getApplicationContext()));
		
		 setupActionBar();
		// BroastcastReceiver
		IntentFilter filter = new IntentFilter("ackMessageChangePwd");
		mReceiver = new PassWordReceive();
		registerReceiver(mReceiver, filter);
		//
	}
	

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		doBindService();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		doUnbindService();

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
	}
	
	private void setupActionBar() {
		ActionBar actionbar = getSupportActionBar();
		actionbar.setCustomView(R.layout.actionbar_setting_activity);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM
				);
		actionbar.setDisplayShowHomeEnabled(false);
		actionbar.setDisplayShowTitleEnabled(false);
		logOut =(TextView)findViewById(R.id.actionbar_setting_activity_logout);
		logOut.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog("Cảnh báo","Bạn có chắc chắn muốn thoát khỏi ứng dụng");
			}
		});
	}
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		try {
			unregisterReceiver(mReceiver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	

	public void doBindService() {
		if (SmartHomeService.isRunning()) {
			bindService(new Intent(getApplicationContext(),
					SmartHomeService.class), mConnection,
					Context.BIND_AUTO_CREATE);

		}
	}

	private void doUnbindService() {
		if (mIsBound) {
			// If we have received the service, and hence registered with it,
			// then now is the time to unregister.

			// Detach our existing connection.
			unbindService(mConnection);
			Log.d("CP", "Unbinding from Service");
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.activity_dialog_pwd_btn_ok:

			String curPwd = currenPwd.getText().toString();
			String nwPwd = newPwd.getText().toString();
			String cfirmPwd = confirmPwd.getText().toString();
			// TODO Auto-generated method stub
			if (!curPwd.equals("") && !nwPwd.equals("")
					&& !cfirmPwd.equals("")) {
				if (curPwd.equals(LumiHome.password)) {
					if (nwPwd.equals(cfirmPwd)) {
						showDialog(PROGRESS_DIALOG_ID);
						Log.e("test", "dialog");
						sendMessageToService(
								NetMessage.CMD_APP_CHANGE_PASSWORD,
								newPwd.getText().toString());
						pwd = nwPwd;						
					} else {
						showDialog("Mật khẩu xác nhận phải trùng với mật khẩu bạn vừa tạo");
					}
				} else {
					showDialog("Bạn đã nhập sai mật khẩu");	
				}
			} else {
				showDialog("Bạn phải điền đầy đủ thông tin");
			}
		
			break;
		
		default:
			break;
		}
	}

	@Override
	@Deprecated
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub

		switch (id) {
		case PROGRESS_DIALOG_ID: {
			ProgressDialog mDialogProgress = new ProgressDialog(this);
			mDialogProgress.setMessage("Đang đổi mật khẩu");
			mDialogProgress.setCancelable(true);
			mDialogProgress.show();
			// Thay doi font chu cua Dialog
			ChangeFont changeFont = new ChangeFont(getApplicationContext());
			TextView textView = (TextView) mDialogProgress
					.findViewById(android.R.id.message);
			textView = changeFont.changeFontTextView(textView,
					"Đang đổi mật khẩu", LumiHome.font, 16,
					Gravity.NO_GRAVITY, getResources().getColor(R.color.white));
			return mDialogProgress;
		}
		}
		return null;
	}

	private void showDialog(String msg) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
//		ErrorDialog.setTitle("Lỗi");
		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvErrorDialog = new TextView(getApplicationContext());
		tvErrorDialog = changeFont.changeFontTextView(tvErrorDialog,
				"Lỗi", LumiHome.fontBold,
				LumiHome.sizeTittle, Gravity.CENTER, getResources()
						.getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvErrorDialog);
		ErrorDialog.setMessage(msg);
		ErrorDialog.setNegativeButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		TextView textView = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
			msg, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.font));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
	}
	private void showDialog(String title, String msg) {
		AlertDialog.Builder ErrorDialog = new AlertDialog.Builder(
				new ContextThemeWrapper(this, R.style.AlertDialogCustom));
		ChangeFont changeFont = new ChangeFont(getApplicationContext());
		TextView tvErrorDialog = new TextView(getApplicationContext());
		tvErrorDialog = changeFont.changeFontTextView(tvErrorDialog,
				title, LumiHome.fontBold,
				LumiHome.sizeTittle, Gravity.CENTER, getResources()
						.getColor(R.color.green));
		ErrorDialog.setCustomTitle(tvErrorDialog);
		ErrorDialog.setMessage(msg);
		ErrorDialog.setNegativeButton("OK",
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						Preference.saveUID(getApplicationContext(), "");
						Preference.savepwd(getApplicationContext(), "");
						Intent intent = new Intent(getApplicationContext(), MainActivity.class);
						intent.putExtra("finish", true);
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);
						finish();
					}
				});
		ErrorDialog.setPositiveButton("Cancel", new DialogInterface.OnClickListener() {
			
			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				dialog.cancel();
			}
		});
		AlertDialog alertErrorDialog = ErrorDialog.create();
		alertErrorDialog.show();
		TextView textView = (TextView) alertErrorDialog
				.findViewById(android.R.id.message);
		textView = changeFont.changeFontTextView(textView,
			msg, LumiHome.font,
				LumiHome.sizeContent, Gravity.NO_GRAVITY, getResources()
						.getColor(R.color.greenActionbar));

		Button btn1 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_NEGATIVE);
		btn1.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.font));
		btn1.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn1.setTextSize(LumiHome.sizeButton);
		Button btn2 = alertErrorDialog
				.getButton(DialogInterface.BUTTON_POSITIVE);
		btn2.setTypeface(Typeface.createFromAsset(getAssets(),
				LumiHome.font));
		btn2.setTextColor(getResources().getColor(R.color.greenActionbar));
		btn2.setTextSize(LumiHome.sizeButton);
	}
	@Override
	public void finish() {
		// TODO Auto-generated method stub
		Intent intentMainActivity = new Intent();
		setResult(RESULT_OK, intentMainActivity);
		super.finish();
	}
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		super.onBackPressed();
		finish();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.content.ServiceConnection#onServiceConnected(android.content.
	 * ComponentName, android.os.IBinder)
	 */
	@Override
	public void onServiceConnected(ComponentName name, IBinder service) {
		// TODO Auto-generated method stub
		mIsBound = true;
		mServiceMessenger = new Messenger(service);

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.content.ServiceConnection#onServiceDisconnected(android.content
	 * .ComponentName)
	 */
	@Override
	public void onServiceDisconnected(ComponentName name) {
		// TODO Auto-generated method stub
		mIsBound = false;
		mServiceMessenger = null;
	}

	private void sendMessageToService(int MsgType, String pass) {
		if (mIsBound) {
			if (mServiceMessenger != null) {
				try {
					Message msg = Message.obtain(null,
							SmartHomeService.UI2SER_NEW_MSG);
					Bundle b = new Bundle();
					b.putInt("Message Type", MsgType);
					// b.putParcelable("ContentProvider Message", appMsg);
					b.putString("PassWord", pass);
					msg.setData(b);
					// msg.replyTo = mMessenger;
					mServiceMessenger.send(msg);
				} catch (RemoteException e) {
				}
			}
		}
	}

	public class PassWordReceive extends BroadcastReceiver {

		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * android.content.BroadcastReceiver#onReceive(android.content.Context,
		 * android.content.Intent)
		 */
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			removeDialog(PROGRESS_DIALOG_ID);
			LumiHome.password = pwd;
			
		}

	}

}
